package pl.edu.romanow

import dispatch.FacebookDispatch.FacebookJobReq
import dispatch.{FacebookDispatch, FacebookJob}
import net.liftweb.actor.LiftActor
import net.liftweb.http.js.JsCmds
import net.liftweb.common.Loggable

/**
 * Created by IntelliJ IDEA.
 * User: jar
 * Date: 04.04.12
 * Time: 01:41
 * To change this template use File | Settings | File Templates.
 */

object Crawler extends LiftActor with Loggable {

  class Servants(id: String) extends LiftActor {
    protected def messageHandler: PartialFunction[Any, Unit] = {
      case job: FacebookJobReq =>
        try {

          logger.info("Proccessing " + job.job.name + "by servant " + id)

          FacebookDispatch.processFacebookJobReq(job, JsCmds.Noop)
        }
        catch {
          case e => logger.error("with job", e)
        }
    }
  }

  val servants = (1 to 15).map(x => new Servants(x.toString)).toArray

  var i = 0;

  def next = {
    i = (i + 1) % servants.size
    servants(i)
  }


  protected override def messageHandler: PartialFunction[Any, Unit] = {
    case job: FacebookJobReq =>
      next ! job
    case list: List[FacebookJobReq] =>
      list.foreach {
        next ! _
      }
    case Fin(obj) => obj.end

  }


  case class Fin(obj: {def end})

}
